import { useEffect, useMemo, useRef, useState, useCallback } from 'react';
import { pinyin } from 'pinyin-pro';
import { useNavigate } from 'react-router-dom';

import { SEARCH } from '@/config/url';
import { getCategoryList } from '@/service/api';
import styles from './index.module.scss';

export default () => {
  const [list, setList] = useState([]);
  const [activeLetter, setActiveLetter] = useState('');
  const containerRef = useRef(null);
  const navigate = useNavigate();

  // 26个大写字符
  const letters = Array.from({ length: 26 }, (_, i) => String.fromCharCode(65 + i));

  // 获取字符首字符对应字母
  const getFirstCharLetter = (str) => {
    if (!str) return '';
    const firstChar = str.charAt(0);
    // 只对第一个字符取拼音首字母
    return pinyin(firstChar, { pattern: 'first' }).toUpperCase();
  }

  const toSearch = obj => {
    const usp = new URLSearchParams();
    usp.set('type', 'category');
    usp.set('q', obj.name);

    // 跳转到搜索页面
    navigate(`${SEARCH}?${usp.toString()}`);
  };
  // 请求分类数据，并格式化数据
  const getData = async () => {
    const [res, err] = await getCategoryList({pageNo: 1, pageSize: 9999});
    if (err) return;

    const letterMap = letters.reduce((acc, l) => { acc[l] = []; return acc; }, {});
    const items = (res.data?.records || []).map((row) => {
      const name = row?.categoryName || '';
      const letter = getFirstCharLetter(name);
      const item = {
        categoryId: row.id,
        name,
        letter,
        icon: (row.categoryImages||'').split(',').filter(Boolean)[0] || '/images/image-holder.svg',
      };
      if (letter && letterMap[letter]) letterMap[letter].push(item);
      return item;
    });

    setList(items);

  };
  useEffect(() => {
    getData();
  }, []);

  const grouped = useMemo(() => {
    const map = new Map();
    letters.forEach(l => map.set(l, []));
    list.forEach(item => {
      const l = item.letter || '#';
      if (!map.has(l)) map.set(l, []);
      map.get(l).push(item);
    });
    const arr = Array.from(map.entries()).map(([letter, items]) => ({ letter, items }));
    return arr;
  }, [list]);

  // 获取滚动容器：优先使用页面级滚动容器
  const getScrollContainer = useCallback(() => {
    // 优先使用发现页滚动容器
    const discoveryEl = document.getElementById('discovery');
    if (discoveryEl) return discoveryEl;
    // 优先页面级容器（PC/Admin）
    const pageEl = document.getElementById('page') || document.getElementById('page-container');
    if (pageEl) return pageEl;
    // 其次移动端/平板布局的 .page/.page-container
    const mobileEl = document.querySelector('.page') || document.querySelector('.page-container');
    if (mobileEl) return mobileEl;
    // 回退到内部容器或文档滚动元素
    return containerRef.current || document.scrollingElement || document.documentElement;
  }, []);

  // 初始化激活字母
  useEffect(() => {
    const firstWithItems = grouped.find(g => (g.items || []).length > 0)?.letter || '';
    setActiveLetter(firstWithItems || '');
  }, [grouped]);

  // 点击右侧字母滚动到对应位置
  const scrollToLetter = useCallback((letter) => {
    const scrollContainer = getScrollContainer();
    const headerEl = document.getElementById(`anchor-${letter}`);
    if (!scrollContainer || !headerEl) return;

    const stickyOffset = 0; // 如有固定头部(例如 44px)，可调整为 44
    const isWindowScroll = [document.body, document.documentElement, document.scrollingElement].includes(scrollContainer);

    if (isWindowScroll) {
      const headerRect = headerEl.getBoundingClientRect();
      const targetTop = window.scrollY + headerRect.top - stickyOffset;
      window.scrollTo({ top: targetTop, behavior: 'smooth' });
    } else {
      const scrollRect = scrollContainer.getBoundingClientRect();
      const headerRect = headerEl.getBoundingClientRect();
      const deltaTop = headerRect.top - scrollRect.top; // 相对滚动容器的顶部偏移
      const targetTop = scrollContainer.scrollTop + deltaTop - stickyOffset;
      if (typeof scrollContainer.scrollTo === 'function') {
        scrollContainer.scrollTo({ top: targetTop, behavior: 'smooth' });
      } else {
        scrollContainer.scrollTop = targetTop;
      }
    }
  }, [getScrollContainer]);

  // 滚动联动 - 根据各锚点标题位置更新激活字母
  useEffect(() => {
    const scrollEl = getScrollContainer();
    if (!scrollEl) return;

    const stickyOffset = 0; // 如有固定头部(例如 44px)，可调整为 44

    const handleScroll = () => {
      // 仅遍历有内容的分组
      const sections = grouped.filter(g => (g.items || []).length > 0);
      if (!sections.length) return;

      const isWindowScroll = [document.body, document.documentElement, document.scrollingElement].includes(scrollEl);
      const scrollTopBase = (isWindowScroll ? window.scrollY : scrollEl.scrollTop) + stickyOffset + 1; // +1避免边界抖动
      let current = sections[0].letter;
      for (let i = 0; i < sections.length; i++) {
        const l = sections[i].letter;
        const header = document.getElementById(`anchor-${l}`);
        if (!header) continue;
        // 计算该标题相对于滚动顶部的距离
        const headerRect = header.getBoundingClientRect();
        const offsetTop = (isWindowScroll ? window.scrollY : scrollEl.scrollTop) + headerRect.top - (isWindowScroll ? 0 : scrollEl.getBoundingClientRect().top);
        if (offsetTop <= scrollTopBase) {
          current = l;
        } else {
          break;
        }
      }
      setActiveLetter(current);
    };

    // 首次同步一次
    handleScroll();
    const isWindowScroll = [document.body, document.documentElement, document.scrollingElement].includes(scrollEl);
    const target = isWindowScroll ? window : scrollEl;
    target.addEventListener('scroll', handleScroll, { passive: true });

    return () => {
      const isWindowScroll = [document.body, document.documentElement, document.scrollingElement].includes(scrollEl);
      const target = isWindowScroll ? window : scrollEl;
      target.removeEventListener('scroll', handleScroll);
    };
  }, [grouped, getScrollContainer]);

  return (
    <div className={styles['category-wrap']}>
      <div className={styles['category-container']} ref={containerRef}>
        {grouped.filter(g => (g.items || []).length > 0).map(({ letter, items }) => (
          <div className={styles['section']} key={letter}>
            <div className={styles['anchor-header']} id={`anchor-${letter}`}>{letter}</div>
            {items.map((it, idx) => (
              <div key={`${letter}-${idx}`} className={styles['item']} onClick={toSearch.bind(null, it)}>
                <div className={styles['item-icon']}>
                  <img src={it.icon ? `${it.icon}?x-oss-process=image/resize,p_20` : '/images/image-holder.svg'} alt={it.name} />
                </div>
                <div className={styles['item-name']}>{it.name}</div>
              </div>
            ))}
          </div>
        ))}
      </div>

      <div className={styles['anchor-sidebar']}>
        {
          letters.map((l) => (
            <div
              key={l}
              className={`${styles['anchor-item']} ${activeLetter === l ? styles['active'] : ''}`}
              onClick={() => scrollToLetter(l)}
            >
              {l}
            </div>
          ))
        }
      </div>
    </div>
  );
}
